// 状态模块
import { Effect, ImmerReducer, history } from 'umi';

import { loginFn } from '@/api/user';

import { message } from 'antd'

// 全局状态中的数据类型
export interface AdminModelState {
    adminname: string;
    role: number
    token: string
    checkedkeys: string[]
    loginState: boolean
}

// 给状态模块添加数据类型用的
export interface AdminModelType {
    namespace: 'admin';
    state: AdminModelState;
    effects: {
        loginAction: Effect;
    };
    reducers: {
        // save: Reducer<IndexModelState>;
        // 启用 immer 之后
        change_info: ImmerReducer<AdminModelState>;
    };
}

const adminModel: AdminModelType = {
    // 模块名称
    namespace: 'admin',
    // 全局状态的初始状态
    state: {
        adminname: localStorage.getItem('adminname') || '',
        role: Number(localStorage.getItem('role')) || 1,
        checkedkeys: JSON.parse(localStorage.getItem('checkedkeys') as string) || [],
        token: localStorage.getItem('token') || '',
        loginState: localStorage.getItem('loginState') === 'true'
    },
    // 异步修改数据的方法
    effects: {
        *loginAction({ payload }, { call, put }): any {

            // call 是用来触发数据请求用的方法
            const res = yield call(loginFn, payload)

            if (res.data.code != 200) {
                // 登录不成功
                message.error('温馨提示：' + res.data.message)
            } else {
                // 登录成功
                message.success('恭喜你登录成功了')
                // 触发修改函数
                res.data.data.loginState = true

                // put 是用来触发修改全局状态用的
                yield put({
                    type: 'change_info',
                    payload: res.data.data
                })

            }

        },
    },
    reducers: {
        // save(state, action) {
        //     return {
        //         ...state,
        //         ...action.payload,
        //     };
        // },
        // 启用 immer 之后
        // save(state, action) {
        //     state.name = action.payload;
        // },
        change_info(state: AdminModelState, actions: any) {




            // 修改数据
            state.adminname = actions.payload.adminname
            state.role = actions.payload.role
            state.checkedkeys = actions.payload.checkedkeys
            state.token = actions.payload.token
            state.loginState = actions.payload.loginState

            localStorage.setItem('adminname', actions.payload.adminname)
            localStorage.setItem('role', actions.payload.role)
            localStorage.setItem('token', actions.payload.token)
            localStorage.setItem('loginState', actions.payload.loginState)
            localStorage.setItem('checkedkeys', JSON.stringify(actions.payload.checkedkeys))

            // console.log(state);
            // 跳转到首页
            history.push('/', {})
        }
    }
};

export default adminModel;